<?php

namespace App\Models\ExpModels;

use App\Models\ParentModel;
use DB;
use App\Components\Tools;

/**
 * 抖音同步用户视频model
 * @author puppet
 */
class ExpCheck extends ParentModel
{
    /**
     * 与模型关联的数据表。
     *
     * @var string
     */
    protected $table = 'pt_exp_ucard';

    /**
     * DB::直接操作的数据库表名
     * @var string
     */
    protected $db_table = 'pt_exp_ucard';

    /**
     * 主键 默认id。
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 指定是否模型应该被戳记时间。
     *
     * @var bool
     */
    public $timestamps = false;

    /*
	*	拉取活动审核列表
	*	type 0待审核，1已通过、未通过	  默认待审核
	*/
	function checkData($params){
		$qiniuUrl=Tools::getOneconfig("/config/third.json",array('qiniu','qnUrl'));
        $size = (isset($params['limit']) && intval($params['limit'])>0 && intval($params['limit']) <= 100) ? $params['limit'] : 5;
        $page = isset($params['page']) ? intval($params['page']) : 1;
        $offset = ($page - 1) * $size;
		
		$type=isset($params['type']) ? intval($params['type']) : 0;
        $search_title=isset($params['search_title']) ? $params['search_title'] : '';
        $search_status=isset($params['search_status']) ? intval($params['search_status']) : 99;
        $search_user=isset($params['search_user']) ? $params['search_user'] : '';
		$sql="select a.*,b.img,b.url,c.type,c.price,c.url as cardImg,c.cill,c.num,c.staTime as sta,c.endTime as end,c.staValid,c.endValid,c.remark as cardR,d.user_name from pt_exp_activity as a";
		$sql.=" left join pt_exp_videos as b on b.id=a.videoId";
		$sql.=" left join pt_exp_card as c on c.id=a.cardId";
        $sql.=" left join pt_partner as d on d.id=a.parnterId";
		$countSql="select count(a.id) as count from pt_exp_activity as a ";
        $countSql.=" left join pt_exp_videos as b on b.id=a.videoId";
        $countSql.=" left join pt_exp_card as c on c.id=a.cardId";
        $countSql.=" left join pt_partner as d on d.id=a.parnterId";
        $countSql.=" where 1=1 ";
		$sql.=" where 1=1 ";

        if($search_title){
            $countSql.=" and a.title like '%{$search_title}%'";
            $sql.=" and a.title like '%{$search_title}%'";
        }
		
		if($search_status!=99){
			$countSql.=" and a.isCheck={$search_status}";
			$sql.=" and a.isCheck={$search_status}";
		}
        if($search_user){
            $countSql.=" and d.user_name like '%{$search_user}%'";
            $sql.=" and d.user_name like '%{$search_user}%'";
        }
        $sql.=" order by a.updateTime desc limit $offset,$size";
		
        $count=DB::select($countSql);
        $count = isset($count[0]['count']) ? $count[0]['count'] : 0;
        $data=DB::select($sql);
        // echo "<pre/>";print_r($countSql);exit;
        if(!empty($data)){
            foreach($data as $k=>$v){
                $data[$k]['title']="<div style=\"max-width:100px;\">".$v['title']." <font style=\"color:#00b7ee;\">{$v['talk']}</font></div>";
                $data[$k]['img']=$v['img'] ? "<img src=\"{$qiniuUrl}/{$v['img']}\" style=\"width:100px;height:80px;cursor:pointer;\" onclick=\"showlayerImg('{$qiniuUrl}/{$v['img']}','视频封面')\">" : "无封面";
				$videoUrl=$qiniuUrl."/".$v['url'];
				$data[$k]['vidoes']="<span style=\"color:#00b7ee;cursor:pointer;\" onclick=\"showlayerVideo('{$qiniuUrl}/{$v['url']}','视频')\">".mb_substr($videoUrl,0,10)."...".mb_substr($videoUrl,-10)."</span>";
				$data[$k]['remark']="<div style=\"max-width:200px;\">".str_replace(["\r\n","\n","\r"],'<br/>',$v['remark'])."</div>";
				$data[$k]['dateTime']=$v['staTime']."<br>".$v['endTime'];
				
				$data[$k]['cardImg']=$v['cardImg'] ? "<img src=\"{$qiniuUrl}/{$v['cardImg']}\" style=\"width:100px;height:80px;cursor:pointer;\" onclick=\"showlayerImg('{$qiniuUrl}/{$v['cardImg']}','卡券图片')\">" : "无卡券";
				$data[$k]['cards']="<div style=\"max-width:210px;\">";
					if($v['cardId']){
						$data[$k]['cards'].=$v['sta'] ? "领取时间：".$v['sta']."<br>" : '无';
						$data[$k]['cards'].=$v['end'] ? "<span style=\"margin-left:70px;\"></span>".$v['end']."<br>" : '';
						
						$data[$k]['cards'].=$v['staValid'] ? "有效时间：".$v['staValid']."<br>" : '';
						$data[$k]['cards'].=$v['endValid'] ? "<span style=\"margin-left:70px;\"></span>".$v['endValid']."<br>" : '';
						
						$typeName=$v['type'] ? $v['type'] : '';
						$typeName=$typeName==1 ? '折扣券' : ($typeName==2 ? '代金券' : '礼品券');
						$data[$k]['cards'].=$v['type'] ? "卡券类型：".$typeName."<br>" : '';
						
						$data[$k]['cards'].="卡券数量：".($v['num'] ? $v['num'] : '无限制')."<br>";
						
						$data[$k]['cards'].="卡券金额：".($v['price'] ? $v['price']/100 : "0")." 元<br>";
						
						$data[$k]['cards'].="使用门槛：".($v['cill'] ? $v['cill'] : 0)." 元";
					}else{
						$data[$k]['cards'].="无";
					}
				$data[$k]['cards'].="</div>";
                $data[$k]['user_name']=$v['user_name'];
				$data[$k]['updateTime']=$v['updateTime'];

				$data[$k]['checkTime']=$v['checkTime'];
				$color=$v['isCheck']==1 ? 'green' : 'red';
				if($v['isCheck']==1){
                    $data[$k]['check'] ="<span style=\"color:{$color};\">已通过</span>";
                    $data[$k]['operation']="<button class=\"btn btn-default btn-sm\" onclick=\"saveActivity('{$v['id']}')\" disabled>通过</button>";
                    $data[$k]['operation'].="<br/><br/>";
                    $data[$k]['operation'].="<button class=\"btn btn-defult btn-sm\" onclick=\"noActivity('{$v['id']}')\" disabled>不通过</button>";
                }elseif($v['isCheck']==2){
                    $data[$k]['check'] ="<span style=\"color:{$color};\">未通过</span>";
                    $data[$k]['operation']="<button class=\"btn btn-default btn-sm\" onclick=\"saveActivity('{$v['id']}')\" disabled>通过</button>";
                    $data[$k]['operation'].="<br/><br/>";
                    $data[$k]['operation'].="<button class=\"btn btn-defult btn-sm\" onclick=\"noActivity('{$v['id']}')\" disabled>不通过</button>";
                }else{
                    $data[$k]['check'] ="<span>未审核</span>";
                    $data[$k]['operation']="<button class=\"btn btn-info btn-sm\" onclick=\"saveActivity('{$v['id']}')\">通过</button>";
                    $data[$k]['operation'].="<br/><br/>";
                    $data[$k]['operation'].="<button class=\"btn btn-defult btn-sm\" onclick=\"noActivity('{$v['id']}')\">不通过</button>";
                }
				$data[$k]['opationName']=$v['opationName'];

            }
        }
        return ['data'=>$data,'total'=>$count];
	}
	
	//审核操作
	function checkSave($kid,$status,$checkTest){
		$data=[
			'isCheck'=>$status,
			'checkTest'=>$checkTest,
			'opationName'=>session('user')[0]['admin_name'],
			'checkTime'=>date('Y-m-d H:i:s')
		];
        // echo "<pre/>";print_r($data);exit;
		return DB::table('pt_exp_activity')->where('id',$kid)->update($data);
	}

    //拉取用户列表
    function userList($partner_id,$title,$page){
        $size = 20;
        $offset = $size * ($page - 1);
        $countSql="select count(a.id) as count from pt_exp_user as a left join pt_exp_activity as b on a.expId=b.id where a.parnterId=?";
        $sql="select a.*,b.title,b.talk from pt_exp_user as a left join pt_exp_activity as b on a.expId=b.id  where a.parnterId=?";
        if($title!=''){
            $countSql.=" and b.title like '%{$title}%'";
            $sql.=" and b.title like '%{$title}%'";
        }
        $sql.=" order by a.create_time desc limit {$offset},{$size}";
        $re=DB::select($sql,[$partner_id]);
        $re=isset($re[0]['id']) ? $re : false;
        $count=DB::select($countSql,[$partner_id]);
        $count=isset($count[0]['count']) ? $count[0]['count'] : 0;
   //  print_r($re);exit();
        $html="";
        $nextPage=$page < ceil($count/$size) ? $page+1 : 0;
        if($re){
            foreach($re as $k=>$v){
                $name=DB::select("select user_name  from pt_partner where id='{$v['parnterId']}'");
                $name=isset($name[0]['user_name']) ? $name[0]['user_name'] : 0;
                $html.="<tr>";
                $html.="<td>$name</td>";
                $html.="<td><img src=\"{$v['avatar']}\" style=\"width:50px;height:50px;cursor:pointer;\" onclick=\"showlayerImg('{$v['avatar']}','')\"></td>";
                $html.="<td>{$v['nickname']}</td>";
                $html.="<td>{$v['mobile']}</td>";
                $html.="<td style=\"white-space:normal;max-width:300px;\">{$v['title']} <font style=\"color: #00b7ee\"> {$v['talk']}</font></td>";
                $html.="<td>{$v['province']}-{$v['city']}</td>";
                $html.="<td>{$v['gender']}</td>";
                $html.="<td>".mb_substr($v['create_time'],0,10)."</td>";
                $html.="</tr>";
            }
        }else{
            $html="<tr><td colspan=\"10\">无数据</td></tr>";
        }
        return json_encode(["code"=>0,"msg"=>$html,"nextPage"=>$nextPage]);
    }
    //拉取用户列表
    function videoList($partner_id,$title,$page){
        $size = 20;
        $qnUrl=Tools::getOneconfig("/config/third.json",array('qiniu','qnUrl'));
        $offset = $size * ($page - 1);
        $countSql="select count(id) as count from pt_exp_videos  where parnterId='$partner_id'";
        $sql="select * from pt_exp_videos   where parnterId='$partner_id'";
        if($title!=''){
            $countSql.=" and title like '%{$title}%'";
            $sql.=" and title like '%{$title}%'";
        }
        $sql.=" order by createtime desc limit {$offset},{$size}";
        $re=DB::select($sql);
        $re=isset($re[0]['id']) ? $re : false;
        $count=DB::select($countSql);
        $count=isset($count[0]['count']) ? $count[0]['count'] : 0;
  //  print_r($sql);exit();
        $html="";
        $nextPage=$page < ceil($count/$size) ? $page+1 : 0;
        if($re){
            foreach($re as $k=>$v){
                $name=DB::select("select user_name  from pt_partner where id='{$v['parnterId']}'");
                $name=isset($name[0]['user_name']) ? $name[0]['user_name'] : 0;
                $html.="<tr>";
                $html.="<td>$name</td>";
                $html.="<td style=\"white-space:normal;min-width:150px;\">{$v['title']}</td>";
                $imgUrl=$v['img'] ? $qnUrl."/".$v['img'] : '';
                if($imgUrl){
                    $html.="<td><img src=\"{$imgUrl}\" style=\"width:50px;height:50px;cursor:pointer;\" onclick=\"showlayerImg('{$imgUrl}','封面')\"></td>";
                }else{
                    $html.="<td>无封面</td>";
                }
                $videoUrl=$qnUrl."/".$v['url'];
                $html.="<td><span onclick=\"showlayerVideo('{$videoUrl}','视频')\" style=\"cursor:pointer;color:#00b7ee;\">".mb_substr($videoUrl,0,10)."...".mb_substr($videoUrl,-10)."</span></td>";
                $html.="<td>{$v['updateTime']}</td>";
                $status=$v['status']==0 ? 'default' : 'checkbox';
                $html.="<td><div class=\"checkbox checkbox-slider--b-flat\"><label><input type=\"{$status}\" checked=\"\" onclick=\"videoupStatus({$v['id']},this)\"><span></span></label></div></td>";
                $html.="<td>";
                $string="{$v['id']},'{$v['title']}','{$imgUrl}','{$qnUrl}/{$v['url']}'";
                $html.="&nbsp;&nbsp;&nbsp;<a href=\"javascript:;\" title=\"修改\" onclick=\"showVideo({$string},this)\"><span class=\"glyphicon glyphicon-pencil\"></span></a>";
                $html.="&nbsp;&nbsp;&nbsp;<a href=\"javascript:;\" title=\"删除\" onclick=\"videodel({$v['id']})\"><span class=\"glyphicon glyphicon-trash\"></span></a>";
                $html.="</td>";
                $html.="</tr>";
            }
        }else{
            $html="<tr><td colspan=\"10\">无数据</td></tr>";
        }
        return json_encode(["code"=>0,"msg"=>$html,"nextPage"=>$nextPage]);
    }

    //拉取用户卡券列表
    function cardList($partner_id,$title,$page){
        $size = 20;
        $qnUrl=Tools::getOneconfig("/config/third.json",array('qiniu','qnUrl'));
        $offset = $size * ($page - 1);
        $countSql="select count(id) as count from pt_exp_card  where parnterId='$partner_id'";
        $sql="select * from pt_exp_card where parnterId='$partner_id'";
        if($title!=''){
            $countSql.=" and title like '%{$title}%'";
            $sql.=" and title like '%{$title}%'";
        }
        $sql.=" order by createtime desc limit {$offset},{$size}";
        $re=DB::select($sql);
        $re=isset($re[0]['id']) ? $re : false;
        $count=DB::select($countSql);
        $count=isset($count[0]['count']) ? $count[0]['count'] : 0;
        //  print_r($sql);exit();
        $html="";
        $nextPage=$page < ceil($count/$size) ? $page+1 : 0;
        if($re){
            foreach($re as $k=>$v){
                $name=DB::select("select user_name  from pt_partner where id='{$v['parnterId']}'");
                $name=isset($name[0]['user_name']) ? $name[0]['user_name'] : 0;
                $html.="<tr data-cill=\"{$v['cill']}\" data-remark=\"{$v['remark']}\">";
                $html.="<td>$name</td>";
                $html.="<td style=\"white-space:normal;min-width:150px;\">{$v['title']}</td>";
                $imgUrl=$qnUrl."/".$v['url'];
                $html.="<td><img src=\"{$imgUrl}\" style=\"width:50px;height:50px;cursor:pointer;\" onclick=\"showlayerImg('{$imgUrl}','图片')\"></td>";
                $html.="<td>".($v['type']==1 ? '折扣券' : ($v['type']==2 ? '代金券' : '礼品券'))."</td>";
                $html.="<td>".($v['num']==-1 ? '无限制' : $v['num'].' 张')."</td>";
                $html.="<td>".($v['price'] ? ($v['price']/100).' 元' : '')."</td>";
                $html.="<td>{$v['cill']} 元</td>";
                $html.="<td style=\"white-space:normal;min-width:200px;\">".str_replace(["\r\n","\n","\r"],'<br/>',$v['remark'])."</td>";
                $html.="<td>{$v['staTime']}<br/>{$v['endTime']}</td>";
                $html.="<td>{$v['staValid']}<br/>{$v['endValid']}</td>";
                $html.="<td>{$v['updateTime']}</td>";
                $status=$v['status']==0 ? 'default' : 'checkbox';
                $html.="<td><div class=\"checkbox checkbox-slider--b-flat\"><label><input type=\"{$status}\" checked=\"\" onclick=\"upStatus({$v['id']},this)\"><span></span></label></div></td>";
                $html.="<td>";
                $string="{$v['id']},'{$v['title']}',{$v['type']},".($v['price']/100).",'{$imgUrl}',".($v['num'] > 0 ? $v['num'] : "''").",'{$v['staTime']}','{$v['endTime']}'";
                $string.=",'{$v['staValid']}','{$v['endValid']}'";
                $html.="&nbsp;&nbsp;&nbsp;<a href=\"javascript:;\" title=\"修改\" onclick=\"edit({$string},this)\"><span class=\"glyphicon glyphicon-pencil\"></span></a>";
                $html.="&nbsp;&nbsp;&nbsp;<a href=\"javascript:;\" title=\"删除\" onclick=\"del({$v['id']})\"><span class=\"glyphicon glyphicon-trash\"></span></a>";
                $html.="</td>";
                $html.="</tr>";
            }
        }else{
            $html="<tr><td colspan=\"10\">无数据</td></tr>";
        }
        return json_encode(["code"=>0,"msg"=>$html,"nextPage"=>$nextPage]);
    }

    //拉取会员的活动数据
    //拉取用户卡券列表
//拉取活动列表
    function actList($partner_id,$title,$page){
        $qnUrl=Tools::getOneconfig("/config/third.json",array('qiniu','qnUrl'));
        $size = 10;
        $offset = $size * ($page - 1);
        $countSql="select count(id) as count from pt_exp_activity where parnterId=? and status!=-1";
        $sql="select a.*,b.nickname,c.url as vurl,d.url as curl,d.num,";

        $sql.="(select count(e.id) from pt_exp_dyv as e where e.expId=a.id) as eNum,";
        $sql.="(select sum(f.play_count) from pt_exp_dyv as f where f.expId=a.id) as fNum,";
        $sql.="(select sum(g.digg_count) from pt_exp_dyv as g where g.expId=a.id) as gNum,";
        $sql.="(select sum(h.comment_count) from pt_exp_dyv as h where h.expId=a.id) as hNum,";
        $sql.="(select sum(j.share_count) from pt_exp_dyv as j where j.expId=a.id) as jNum,";
        $sql.="(select count(k.id) from pt_exp_ucard as k where k.expId=a.id) as kNum";

        $sql.=" from pt_exp_activity as a";
        $sql.=" left join pt_user as b on b.open_id=a.openId and partner_id={$partner_id}";
        $sql.=" left join pt_exp_videos as c on c.id=a.videoId";
        $sql.=" left join pt_exp_card as d on d.id=a.cardId";
        $sql.=" where a.parnterId=? and a.status!=-1";
        if($title!=''){
            $countSql.=" and (title like '%{$title}%' or talk like '%{$title}%')";
            $sql.=" and (a.title like '%{$title}%' or a.talk like '%{$title}%')";
        }
        $sql.=" order by a.updateTime desc limit {$offset},{$size}";
        $re=DB::select($sql,[$partner_id]);
        $re=isset($re[0]['id']) ? $re : false;
        $count=DB::select($countSql,[$partner_id]);
        $count=isset($count[0]['count']) ? $count[0]['count'] : 0;

        $html="";
        $nextPage=$page < ceil($count/$size) ? $page+1 : 0;
        //print_r($re);exit();
        if($re){
            foreach($re as $k=>$v){
                $name=DB::select("select user_name  from pt_partner where id='{$v['parnterId']}'");
                $name=isset($name[0]['user_name']) ? $name[0]['user_name'] : 0;
                $html.="<tr data-remark=\"{$v['remark']}\">";
                $html.="<td>$name</td>";
                $html.="<td style=\"white-space:normal;max-width:300px;\">{$v['title']} <font style=\"color:#00b7ee;\">{$v['talk']}</font></td>";
                $html.="<td style=\"white-space:normal;max-width:300px;\">".str_replace(["\r\n","\n","\r"],'<br/>',$v['remark'])."</td>";
                $html.="<td>{$v['staTime']}<br/>{$v['endTime']}</td>";

                $html.="<td>".($v['kNum'] ? $v['kNum'] : 0)." / ".($v['num']>0 ? $v['num'] : '无限制')."</td>";
                // $html.="<td style=\"text-align: center\"><a href=\"javascript:;\" title=\"查看卡卷使用情况\"><span class=\"glyphicon glyphicon-eye-open\" onclick=\"showCardUserinfo('{$v['id']}','{$v['title']}')\"></span></a></td>";
                $html.="<td>".($v['eNum'] ? $v['eNum'] : 0)."</td>";
                $html.="<td>".($v['fNum'] ? $v['fNum'] : 0)."</td>";
                $html.="<td>".($v['gNum'] ? $v['gNum'] : 0)."</td>";
                $html.="<td>".($v['hNum'] ? $v['hNum'] : 0)."</td>";
                $html.="<td>".($v['jNum'] ? $v['jNum'] : 0)."</td>";
                $html.="<td>{$v['updateTime']}</td>";
                $status=$v['status']==0 ? 'default' : 'checkbox';
                $html.="<td><div class=\"checkbox checkbox-slider--b-flat\"><label><input type=\"{$status}\" checked=\"\" onclick=\"upactStatus({$v['id']},this)\"><span></span></label></div></td>";

                if($v['isCheck']==0){
                    $html.="<td>待审核</td>";
                }elseif($v['isCheck']==1){
                    $html.="<td style=\"color:green;\">已通过</td>";
                }else{
                    $html.="<td style=\"color:red;white-space:normal;max-width:200px;\">未通过：{$v['checkTest']}</td>";
                }

                $html.="<td>";
                $string="{$v['id']},'{$v['title']}','{$v['talk']}','{$v['openId']}','{$v['nickname']}','{$v['posInurl']}','{$v['poiName']}','{$v['poiId']}','{$v['poiAddress']}','{$v['poiCity']}'";
                $string.=",'{$v['videoId']}','{$v['cardId']}','{$v['staTime']}','{$v['endTime']}','{$qnUrl}/{$v['vurl']}','{$qnUrl}/{$v['curl']}'";
                $html.="<a href=\"javascript:;\" title=\"查看-修改\" onclick=\"actedit({$string},this)\"><span class=\"glyphicon glyphicon-eye-open\"></span></a>";
                $html.="&nbsp;&nbsp;&nbsp;<a href=\"javascript:;\" title=\"删除\" onclick=\"actdel({$v['id']})\"><span class=\"glyphicon glyphicon-trash\"></span></a>";

                if($v['isCheck']==1){//审核通过显示二维码
                    $client_key=Tools::getOneconfig("/config/third.json",array('douyin','dy_client_key'));
                    $scope="video.create,video.delete,video.data,video.list,user_info,renew_refresh_token,mobile_alert,mobile,data.external.item";
                    $redirect_uri=Tools::getOneconfig("/config/third.json",array('douyin','dy_bank_url'));
                    $url="http://open.douyin.com/platform/oauth/connect/?client_key={$client_key}&response_type=code&scope={$scope}&redirect_uri={$redirect_uri}/exp/banck&state={$v['id']}";
                    $html.="&nbsp;&nbsp;&nbsp;<a href=\"javascript:;\" title=\"二维码\" onclick=\"qrCodeDown('showQrcode','{$url}','活动二维码','{$v['title']}')\"><span class=\"fa fa-qrcode\"></span></a>";
                }
                $html.="</td>";
                $html.="</tr>";
            }
        }else{
            $html="<tr><td colspan=\"10\">无数据</td></tr>";
        }
        return json_encode(["code"=>0,"msg"=>$html,"nextPage"=>$nextPage]);
    }

}